import { contextBridge, ipcRenderer } from 'electron'

import { EVENTS } from './events'
import { electronAPI } from '@electron-toolkit/preload'

// Custom APIs for renderer
const api = {
  toggleTrafficLight: (isShow) => ipcRenderer.send(EVENTS.toggleTrafficLight, isShow),
  loadCustomFonts: () => ipcRenderer.send(EVENTS.loadCustomFont),
  removeCustomFont: (fontPath) => ipcRenderer.send(EVENTS.removeCustomFont, fontPath),
  fileDataChange: (fileId, value, fileTree) =>
    ipcRenderer.send(EVENTS.fileDataChange, fileId, value, fileTree),
  onLoadCustomFontSuccess: (cb) => ipcRenderer.on(EVENTS.loadCustomFontSuccess, cb),
  onRemoveCustomFontSuccess: (cb) => ipcRenderer.on(EVENTS.removeCustomFontSuccess, cb),
  switchFontfamily: (fontName) => ipcRenderer.send(EVENTS.switchFontfamily, fontName),
  customStoragePath: () => ipcRenderer.send(EVENTS.customStoragePath),
  customStoragePathSuccess: (cb) => ipcRenderer.on(EVENTS.customStoragePathSuccess, cb),
  openStoragePath: (storagePath) => ipcRenderer.send(EVENTS.openStoragePath, storagePath),
  showItemInFolder: (itemId, fileTree) =>
    ipcRenderer.send(EVENTS.showItemInFolder, itemId, fileTree),
  addFile: (fileId, value, fileTree) => ipcRenderer.send(EVENTS.addFile, fileId, value, fileTree),
  deleteFileOrFolder: (fileId, fileTree) =>
    ipcRenderer.send(EVENTS.deleteFileOrFolder, fileId, fileTree),
  renameFileOrFolder: (fileId, newName, fileTree) =>
    ipcRenderer.send(EVENTS.renameFileOrFolder, fileId, newName, fileTree),
  dragAndDrop: (items, parentId, fileTree) => {
    ipcRenderer.send(EVENTS.dragAndDrop, items, parentId, fileTree)
  },
  openFileSuccess: (cb) => ipcRenderer.on(EVENTS.openFileSuccess, cb),
  openRevezoneLinkSuccess: (cb) => ipcRenderer.on(EVENTS.openRevezoneLinkSuccess, cb),
  removeAllRevezoneLinkListeners: () =>
    ipcRenderer.removeAllListeners(EVENTS.openRevezoneLinkSuccess)
}

// Use `contextBridge` APIs to expose Electron APIs to
// renderer only if context isolation is enabled, otherwise
// just add to the DOM global.
if (process.contextIsolated) {
  try {
    contextBridge.exposeInMainWorld('electron', electronAPI)
    contextBridge.exposeInMainWorld('api', api)
  } catch (error) {
    console.error(error)
  }
} else {
  window.electron = electronAPI
  window.api = api
}
